﻿// description  : 授权服务
// author       : tristan
// created      : 2011/2/16
// contact      : snaprack@gmail.com

namespace RBAC
{
    using System.Linq;
    using System.Collections.Generic;


    /// <summary>
    /// 授权服务
    /// </summary>
    public class Authorization
    {
        /// <summary>
        /// 获取和设置用户账户
        /// </summary>
        protected Account _user;
        /// <summary>
        /// 构造一个授权服务实例
        /// </summary>
        /// <param name="user">用户名</param>
        public Authorization(string user)
        {
            Init(user);
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="user">用户ID</param>
        protected virtual void Init(string user)
        {
            _user = Account.Load(user);
        }
        /// <summary>
        /// 返回资源是否已授权
        /// </summary>
        /// <param name="resource">资源编码</param>
        public virtual bool IsAuthorized(string resource)
        {
            var dest = _user.GetRoles()
                .Any<Role>(role => role.GetResources()
                    .Any<Resource>(res => res.ID == resource));

            return dest;
        }
        /// <summary>
        /// 获得已授权的资源清单
        /// </summary>
        public virtual IEnumerable<string> GetResources()
        {
            foreach (Role role in _user.GetRoles()){
                foreach(Resource res in role.GetResources()){
                    yield return res.ID;
                }
            }

        }
    }
}
